<?php

class Tool_dir{
  public static function path2path_protected($_dir){
    if($_dir[strlen($_dir)-1] !== '/'){
      $_dir .= '/';
    }
    return $_dir;
  }


  public static function get_files($_dir){
    $dir = self::path2path_protected($_dir);
    $rep = opendir($dir);
    $array = array();
    while($f = readdir($rep)){
      if($f != '..' && $f !='.' && $f !=''){
        array_push($array,"$dir$f");
      }
    }
    closedir($rep);
    clearstatcache();
    return $array;
  }


  public static function get_files_type($_dir){
    $array_from_dir = self::get_files($_dir);
    $all_files_by_type = array();
    foreach($array_from_dir as $path){
      $type = array_pop(@explode(".",$path));
      if(array_key_exists($type,$all_files_by_type))
        array_push($all_files_by_type[$type],$path);
      else $all_files_by_type[$type]=array($path);
    }
    return $all_files_by_type;
  }

  public static function get_files_regexp($_dir,$_reg_exp){
    $_dir = self::path2path_protected($_dir);
    $rep = opendir($_dir);
    $array = array();
    while($f = readdir($rep)){
      if($f != '..' && $f !='.' && $f !=''){
        $nb_res = preg_match($_reg_exp, $f);
        if($nb_res > 0){
          array_push($array,"$_dir$f");
        }
      }
    }
    closedir($rep);
    clearstatcache();
    return $array;
  }

  //
  // En fonction d'un répertoire et d'une expression régulière
  //   - récupère les patrons uniques qui répondent correctement à la regexp
  //

  public static function get_all_ids($_dir,$_rule_id){
    $array_path = self::get_files($_dir);
    $all_ids = array();
    foreach($array_path as $path){
      if(preg_match($_rule_id ,$path,$id)){
        if(!in_array($id[0],$all_ids)){
          $all_ids[] = $id[0];
        }
      }
    }
    return $all_ids;
  }


}

?>
